package com.itheima.kafka.example3;

import com.alibaba.fastjson.JSON;
import com.itheima.kafka.pojos.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * 订单消息消费者
 */
@Slf4j
@Component
public class OrderListener {
    
    /**
     * 监听订单消息
     */
    @KafkaListener(topics = "orders", groupId = "order-consumer-group")
    public void handleOrder(String message) {
        try {
            // 解析JSON为Order对象
            Order order = JSON.parseObject(message, Order.class);
            
            log.info("═══════════════════════════════════════");
            log.info("📥 [订单消费者] 收到订单消息");
            log.info("📥 订单ID: {}", order.getOrderId());
            
            if (order.getProductName() != null) {
                log.info("📥 产品名称: {}", order.getProductName());
                log.info("📥 购买数量: {}", order.getQuantity());
                log.info("📥 订单金额: ¥{}", order.getPrice());
            }
            
            log.info("📥 订单状态: {}", order.getStatus());
            
            // 模拟订单处理
            processOrder(order);
            
            log.info("═══════════════════════════════════════");
            
        } catch (Exception e) {
            log.error("❌ [订单消费者] 处理订单消息失败: {}", e.getMessage(), e);
        }
    }
    
    /**
     * 处理订单业务逻辑
     */
    private void processOrder(Order order) {
        String status = order.getStatus();
        
        switch (status) {
            case "PENDING":
                log.info("✅ [订单处理] 订单 {} 进入待处理队列", order.getOrderId());
                log.info("✅ [订单处理] 开始验证库存...");
                break;
                
            case "PROCESSING":
                log.info("🔄 [订单处理] 订单 {} 正在处理中", order.getOrderId());
                log.info("🔄 [订单处理] 准备发货...");
                break;
                
            case "COMPLETED":
                log.info("🎉 [订单处理] 订单 {} 已完成", order.getOrderId());
                log.info("🎉 [订单处理] 感谢您的购买！");
                break;
                
            case "CANCELLED":
                log.info("⚠️ [订单处理] 订单 {} 已取消", order.getOrderId());
                break;
                
            default:
                log.warn("⚠️ [订单处理] 未知状态: {}", status);
        }
        
        // 模拟处理延迟
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

